#!/bin/bash

ROOT=`pwd | grep /tools`
if [ -z "$ROOT" ]; then
ROOT=`pwd`
else
ROOT=`echo ${ROOT/\/tools/}`
fi
echo "ROOT: ${ROOT}"

source ${ROOT}/tools/pack.sh

function start_http_server(){
    http-server ${ROOT}/build -p 8471 --cors
}

function ota_udp_send(){
    udp_addr="238.84.84.71"
    udp_port="8471"
    echo $1
    echo $1 | nc -w 1 -u $udp_addr $udp_port
    # echo $1 | socat - udp-datagram:$udp_addr:$udp_port
}

function ota_udp(){
    cd ${ROOT}/build
    bin_file=`ls | grep *.elf`
    if [ -z "$bin_file" ]; then
        echo "没有编译文件"
        exit 1
    fi
    project=`echo ${bin_file/.elf/}`
    echo "项目名称为 $project"
    bin_file=`echo ${bin_file/.elf/.bin}`
    echo "升级文件为 $bin_file"
    # ip=`ifconfig | grep "broadcast" | awk '{print $2}'`
    ip=`hostname -I | awk '{print $1}'`
    echo "当前IP为 $ip"
    echo "ota app $ip 8471 /$bin_file"
    fun_name="app"
    if [ "$1" == "storage" ];then
        fun_name="storage"
        bin_file="storage.bin"
    elif [ "$1" == "www" ];then
        fun_name="www"
        bin_file="www.bin"
    elif [ "$1" == "ttf" ];then
        fun_name="ttf"
        bin_file="ttf.bin"
    elif [ "$1" == "ttg" ];then
        fun_name="ttg"
        bin_file="TTG.bin"
    fi
    ota_udp_send "TTGOTA $fun_name $ip 8471 /$bin_file"
    # echo "ota app $ip 8471 /$bin_file" | nc -w 1 -u 238.84.84.71 8471
    
    cd ${ROOT}
}

function get_pem(){
    openssl s_client -showcerts -connect gitee.com:443 < /dev/null \
    2> /dev/null | openssl x509 -outform PEM > certs/gitee.pem

    openssl s_client -showcerts -connect gitee.com:443 </dev/null
}

function tools(){
    if [ "$1" == "pack" ]; then
        pack $2
    elif [ "$1" == "clear" ]; then
        pack_clear
    elif [ "$1" == "server" ]; then
        start_http_server
    elif [ "$1" == "get_pem" ]; then
        get_pem $2
    elif [ "$1" == "ota" ]; then
        if [ "$2" == "udp" ];then
        ota_udp $3 $4 $5 $6
        fi
    else
        echo "请输入正确的参数"
        echo "tools pack"
        echo "tools server"
        echo "tools ota udp"
    fi
}
tools "$@"